package com.xh.bussiness.practice.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.practice.bean.dto.PracticeDto;
import com.xh.bussiness.practice.bean.dto.PracticeDtoVO;
import com.xh.bussiness.practice.bean.dto.PracticeGroupByDateDto;
import com.xh.bussiness.practice.bean.request.PracticeDetailRequest;
import com.xh.bussiness.practice.bean.request.PracticeRequest;
import com.xh.bussiness.practice.bean.request.SavePracticeRequest;
import com.xh.bussiness.practice.constant.PracticeConstant;
import com.xh.bussiness.practice.model.Practice;
import com.xh.bussiness.practice.dao.PracticeMapper;
import com.xh.bussiness.practice.model.PracticeDetail;
import com.xh.bussiness.practice.model.PracticeStudent;
import com.xh.bussiness.practice.model.PracticeStudentResult;
import com.xh.bussiness.practice.service.IPracticeDetailService;
import com.xh.bussiness.practice.service.IPracticeService;
import com.xh.bussiness.practice.service.IPracticeStudentResultService;
import com.xh.bussiness.practice.service.IPracticeStudentService;
import com.xh.bussiness.system.model.Student;
import com.xh.bussiness.system.service.IDictionaryService;
import com.xh.bussiness.tiku.bean.dto.PaperChapterDto;
import com.xh.bussiness.tiku.bean.dto.PaperDto;
import com.xh.bussiness.tiku.bean.dto.PaperQuestionDto;
import com.xh.bussiness.tiku.bean.dto.QuestionDto;
import com.xh.bussiness.tiku.model.Paper;
import com.xh.bussiness.tiku.model.Question;
import com.xh.bussiness.tiku.service.IPaperService;
import com.xh.bussiness.tms.model.Class;
import com.xh.bussiness.tms.model.ClassStudent;
import com.xh.bussiness.tms.service.IClassStudentService;
import com.xh.core.bean.AjaxResult;
import com.xh.core.exception.XhException;
import com.xh.core.service.impl.BaseServiceImpl;
import com.xh.core.util.DateUtils;
import com.xh.core.util.MathUtils;
import com.xh.core.util.StringUtils;
import com.xh.core.util.UserUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xh.core.bean.XhPage;
import org.springframework.util.CollectionUtils;

import java.text.NumberFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 作业表 服务实现类
 * </p>
 *
 * @author Pitt
 * @since 2021-01-26
 */
@Service
public class PracticeServiceImpl extends BaseServiceImpl<PracticeMapper, Practice> implements IPracticeService {
    @Autowired
    private IPracticeDetailService practiceDetailService;
    @Autowired
    private IPracticeStudentService practiceStudentService;
    @Autowired
    private IPracticeStudentResultService practiceStudentResultService;
    @Autowired
    private IPaperService paperService;
    @Autowired
    private IDictionaryService dictionaryService;
    @Autowired
    private IClassStudentService studentService;
    @Override
    public Map<String, List<Practice>> queryPracticePage(XhPage page, PracticeRequest bean) {
        QueryWrapper qw=new QueryWrapper<Practice>();
        //拼装条件
        qw=prepareParams(bean, qw);

        XhPage result = (XhPage) this.dao.selectPage(page,qw);
        List<Practice> list = result.getRecords();
        Map<String, List<Practice>> map = new LinkedHashMap();
        Date now = new Date();
        for (Practice practice : list) {
            String dateStr = DateUtils.format(practice.getPublishTime(),"MM月dd日");
            if(dateStr.equals(DateUtils.format(now,"MM月dd日"))){
                dateStr = "今日作业";
            }
            List<Practice> practices = map.get(dateStr) == null ? new ArrayList<>() : map.get(dateStr);
            practices.add(practice);
            map.put(dateStr,practices);
        }
        return map;
    }

    @Override
    public List queryPractice(PracticeRequest bean) {
        QueryWrapper qw=new QueryWrapper<Practice>();
        //拼装条件
        qw=prepareParams(bean, qw);

        return this.dao.selectList(qw);
    }

    @Override
    public String publishPractice(SavePracticeRequest request) {
        String msg = request.checkVal();
        if (!StringUtils.isEmpty(msg)) {
            return msg;
        }
        //普通作业
        if (request.getType().equals(PracticeConstant.PRACTICE_COMMON)) {
            if (StringUtils.isEmpty(request.getContent()) && CollectionUtils.isEmpty(request.getPracticeDetails())) {
                return "作业内容不能为空";
            }
        }
        Date oldPublishTime = null;
        Date createTime = null;
        if (!StringUtils.isEmpty(request.getId())) {
            Practice practice = this.getById(request.getId());
            if (practice == null) {
                return "作业不存在";
            }
            if (practice.getStatus().equals(3)) {
                return "作业已被作答，修改失败";
            }
//            oldPublishTime = practice.getPublishTime();
            createTime = practice.getCreateTime();
            this.deleteById(request.getId());
        }
        Practice practice = new Practice();
        BeanUtils.copyProperties(request, practice);
        if(createTime!=null){
            practice.setCreateTime(createTime);
        }
        if (!StringUtils.isEmpty(request.getPaperId())) {
            Paper paper = paperService.getById(request.getPaperId());
            if (paper == null) {
                return "试卷不存在";
            }
            practice.setSubjectId(paper.getSubjectId());
            if (StringUtils.isEmpty(paper.getSubjectId())) {
                practice.setSubjectName(dictionaryService.queryByCode(paper.getSubjectId(),"SUBJECT").getName());
            }
        }
        if (!StringUtils.isEmpty(request.getStartTime())) {
            practice.setStartTime(DateUtils.parse(request.getStartTime().replaceAll("\\(.*\\)"," "), "yyyy-MM-dd HH:mm:ss"));
        }
        if (!StringUtils.isEmpty(request.getEndTime())) {
            practice.setEndTime(DateUtils.parse(request.getEndTime().replaceAll("\\(.*\\)"," "), "yyyy-MM-dd HH:mm:ss"));
        }
        //提醒时间
        if (!StringUtils.isEmpty(request.getRemindTime())) {
            //提醒时间cron表达式,用于生成定时任务
            String cron = DateUtils.getCron(DateUtils.parse(request.getRemindTime().replaceAll("\\(.*\\)"," "), "yyyy-MM-dd HH:mm:ss"));
            practice.setTimingCron(cron);
            practice.setRemindTime(DateUtils.parse(request.getRemindTime().replaceAll("\\(.*\\)"," "), "yyyy-MM-dd HH:mm:ss"));
        }
//        if (oldPublishTime == null) {
//            practice.setPublishTime(new Date());
//        }else{
//            practice.setPublishTime(oldPublishTime);
//        }

        if(practice.getStartTime()==null) {
            practice.setPublishTime(new Date());
//            practice.setStartTime(new Date());
        }else {
            practice.setPublishTime(practice.getStartTime());
        }
        this.insert(practice);
        //普通作业
        if (request.getType().equals(PracticeConstant.PRACTICE_COMMON)) {
            if (!StringUtils.isEmpty(request.getContent())) {
                PracticeDetail practiceDetail = new PracticeDetail();
                practiceDetail.setPracticeId(practice.getId());
                practiceDetail.setContent(request.getContent());
                //文本
                practiceDetail.setFileType(5);
                practiceDetailService.insert(practiceDetail);
            }
            if (!CollectionUtils.isEmpty(request.getPracticeDetails())) {
                for (PracticeDetail practiceDetail : request.getPracticeDetails()) {
                    PracticeDetail detail = new PracticeDetail();
                    BeanUtils.copyProperties(practiceDetail, detail);
                    detail.setPracticeId(practice.getId());

                    practiceDetailService.insert(detail);
                }
            }
        }
        //已发布保存学生作业
        if (request.getStatus().equals(1)) {
            savePracticeStudent(request,practice);
        }
        return null;
    }

    @Override
    public XhPage<PracticeGroupByDateDto> queryPublishPracticePage(PracticeRequest bean) {
        XhPage xhPage = new XhPage();
        xhPage.setCurrent(bean.getCurrent());
        xhPage.setSize(bean.getSize());
        QueryWrapper qw=new QueryWrapper<Practice>();
        //拼装条件
        qw=prepareParams(bean, qw);
        xhPage = (XhPage) this.dao.selectPage(xhPage, qw);

        if (CollectionUtils.isEmpty(xhPage.getRecords())) {
            return xhPage;
        }
        List<Practice> practices = xhPage.getRecords();
        //按发布时间分组
        List<PracticeGroupByDateDto> resultList = new ArrayList<>();
        Map<String, List<Practice>> practiceGroupMaps = practices.stream().collect(Collectors.groupingBy(item -> DateUtils.format(item.getPublishTime(), "yyyy-MM-dd")));
        practiceGroupMaps.forEach((k,v)-> {
            if (!CollectionUtils.isEmpty(v)) {
                PracticeGroupByDateDto dateDto = new PracticeGroupByDateDto();
                dateDto.setPublishDate(k);
                dateDto.setPublishTime(DateUtils.parse(k, "yyyy-MM-dd"));
                List<PracticeDto> dtos = new ArrayList<>();
                for (Practice practice : v) {
                    PracticeDto practiceDto = convertPracticeDto(practice);
                    List<PracticeStudent> practiceStudents = practiceStudentService.queryByPracticeId(practice.getId());
                    practiceDto.setUnSubmitCount(0);
                    practiceDto.setSubmitCount(0);
                    practiceDto.setSubmitRate(0.0);
                    practiceDto.setClassNames(practice.getClassNames());
                    if (!CollectionUtils.isEmpty(practiceStudents)) {
                        Long unsubmitCount = practiceStudents.stream().filter(item -> item.getStatus().equals(0)).count();
                        Long submitCount = practiceStudents.stream().filter(item -> !item.getStatus().equals(0)).count();

                        practiceDto.setUnSubmitCount(unsubmitCount.intValue());
                        practiceDto.setSubmitCount(submitCount.intValue());
                        practiceDto.setSubmitRate(MathUtils.getNumberRate(MathUtils.divTwoNumberRoundHalfUp(submitCount, practiceStudents.size(), 2), 2));
                    }
                    dtos.add(practiceDto);
                }
                if (!CollectionUtils.isEmpty(dtos)) {
                    dateDto.setPracticeDtos(dtos);
                }
                resultList.add(dateDto);
            }
        });
        if (!CollectionUtils.isEmpty(resultList)) {
            xhPage.setRecords(resultList.stream().sorted(Comparator.comparing(PracticeGroupByDateDto::getPublishTime).reversed()).collect(Collectors.toList()));
        }else{
            xhPage.setRecords(new ArrayList());
        }
        return xhPage;
    }

    private PracticeDto convertPracticeDto(Practice practice) {
        PracticeDto practiceDto = new PracticeDto();
        BeanUtils.copyProperties(practice, practiceDto);
//        practiceDto.setPublishTime(DateUtils.format(practice.getPublishTime(), "yyyy-MM-dd HH:mm:ss"));
        practiceDto.setPublishTime(practice.getPublishTime());
        if (practice.getStartTime() != null) {
//            practiceDto.setStartTime(DateUtils.format(practice.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
            practiceDto.setStartTime(practice.getStartTime());
        }
        if (practice.getEndTime() != null) {
//            practiceDto.setEndTime(DateUtils.format(practice.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
            practiceDto.setEndTime(practice.getEndTime());
        }
        if (practice.getRemindTime() != null) {
//            practiceDto.setRemindTime(DateUtils.format(practice.getRemindTime(), "yyyy-MM-dd HH:mm:ss"));
            practiceDto.setRemindTime(practice.getRemindTime());
        }
        if (!StringUtils.isEmpty(practice.getClassIds())) {
            practiceDto.setClassIds(practice.getClassIds().split(","));
        }
        if (!StringUtils.isEmpty(practice.getSubmitType())) {
            practiceDto.setSubmitType(practice.getSubmitType().split(","));
        }
        return practiceDto;
    }

    @Override
    public PracticeDto queryPracticeDetailById(String practiceId) {
        Practice practice = this.getById(practiceId);
        if (practice == null) {
            throw new XhException("作业不存在");
        }
        PracticeDto practiceDto = convertPracticeDto(practice);
        if (!StringUtils.isEmpty(practice.getPaperId())) {
            Paper paper = paperService.getById(practice.getPaperId());
            if (paper != null) {
                practiceDto.setPaperName(paper.getTitle());
            }
        }
        //普通作业
        if (practice.getType().equals(PracticeConstant.PRACTICE_COMMON)) {
            PracticeDetailRequest detailRequest = new PracticeDetailRequest();
            detailRequest.setPracticeId(practiceId);
            List<PracticeDetail> list = practiceDetailService.queryPracticeDetail(detailRequest);
            if (!CollectionUtils.isEmpty(list)) {
                practiceDto.setPracticeDetails(list);
            }
        } else if (practice.getType().equals(PracticeConstant.PRACTICE_TIKU) && !StringUtils.isEmpty(practice.getPaperId())) {
            //题库作业
            List<QuestionDto> questionDtos = new ArrayList<>();
            PaperDto paper = paperService.getPracticePaper(practice.getPaperId());
            if (paper != null) {
                if (!CollectionUtils.isEmpty(paper.getPaperCharpts())) {
                    //试卷章节
                    for (PaperChapterDto paperCharpt : paper.getPaperCharpts()) {
                        if (!CollectionUtils.isEmpty(paperCharpt.getQuestions())) {
                            //章节试题
                            for (PaperQuestionDto paperQuestionDto : paperCharpt.getQuestions()) {
                                QuestionDto question = paperQuestionDto.getQuestion();
                                if (question != null) {
                                    question.setKnowledges(null);
                                    question.setKnowledgePoints(null);
                                    question.setScore(paperQuestionDto.getScore());
                                    questionDtos.add(question);
                                }
                            }
                        }
                    }
                } else if (!CollectionUtils.isEmpty(paper.getQuestions())) {
                    questionDtos.addAll(paper.getQuestions().stream().map(PaperQuestionDto::getQuestion).collect(Collectors.toList()));
                }
            }
            practiceDto.setQuestions(questionDtos);
        }

        List<PracticeStudent> practiceStudents = practiceStudentService.queryByPracticeId(practiceId);
        if (!CollectionUtils.isEmpty(practiceStudents)) {
            Map<String, List<PracticeStudent>> classMaps = practiceStudents.stream().collect(Collectors.groupingBy(item -> item.getClassId()));
            if (!CollectionUtils.isEmpty(classMaps)) {
                List<Class> classes = new ArrayList<>();
                classMaps.forEach((k,v)->{
                    Class cls = new Class();
                    cls.setId(k);
                    if (!CollectionUtils.isEmpty(v)) {
                        List<Student> students = new ArrayList<>();
                        for (PracticeStudent practiceStudent : v) {
                            Student student = new Student();
                            student.setId(practiceStudent.getStudentId());
                            students.add(student);
                        }
                        cls.setStudents(students);
                    }
                    classes.add(cls);
                });
                practiceDto.setClasses(classes);
            }
        }
        return practiceDto;
    }

    @Override
    public XhPage queryPracticeByClassId(XhPage page, PracticeRequest bean) {
        XhPage<Practice> xhPage = new XhPage();
        xhPage.setCurrent(bean.getCurrent());
        xhPage.setSize(bean.getSize());
        QueryWrapper qw=new QueryWrapper<Practice>();
        //拼装条件
        qw=prepareParams(bean, qw);
        this.dao.selectPage(xhPage, qw);
        List<Practice> practices = xhPage.getRecords();
        QueryWrapper<ClassStudent> qwStudent= new QueryWrapper<>();
        qwStudent.eq("class_id",bean.getClassId());
        Integer studentCount = studentService.selectCount(qwStudent);//学生总数

        for(Practice practice : practices){
            List<PracticeStudent> practiceStudents = practiceStudentService.queryPracticeStudentStatusCount(practice.getId());
            practice.setUncommittedCount(0);
            practice.setCommittedCount(0);
            practice.setCheckedCount(0);
            practice.setDraftCount(0);
            practice.setStudentCount(studentCount);//学生总数
            Integer sendCount = 0;
            Integer committedCount = 0;
            for (PracticeStudent student : practiceStudents){
                Integer status = student.getStatus();
                Integer statusCount = student.getStatusCount()==null ? 0:student.getStatusCount();
                //状态（0：未提交；1：已提交；2：已批改 3：草稿)
                switch (status){
                    case 0:practice.setUncommittedCount(statusCount);sendCount+=statusCount;break;
                    case 1:committedCount+=statusCount;sendCount+=statusCount;break;
                    case 2:practice.setCheckedCount(statusCount);
                           committedCount+=statusCount;
                           sendCount+=statusCount;break;
                    case 3:practice.setDraftCount(statusCount);break;
                }
            }
            practice.setCommittedCount(committedCount);//已提交人数
            practice.setSendCount(sendCount);//发布人数
        }
        return xhPage;
    }

    private void savePracticeStudent(SavePracticeRequest request, Practice practice) {
        //保存学生作业信息
        if (!CollectionUtils.isEmpty(request.getClassStudents())) {
            List<String> clsIds = new ArrayList<>();
            List<String> clsNames = new ArrayList<>();
            List<Student> students = new ArrayList<>();

            //原方法
//            for (Class clazz : request.getClassStudents()) {
//                List<PracticeStudent> practiceStudents = new ArrayList<>();
//                clsIds.add(clazz.getId());
//                clsNames.add(clazz.getTitle());
//                if (!CollectionUtils.isEmpty(clazz.getStudents())) {
//                    for (Student student : clazz.getStudents()) {
//                        PracticeStudent practiceStudent = new PracticeStudent();
//                        practiceStudent.setPracticeId(practice.getId());
//                        practiceStudent.setUserId(practice.getUserId());
//                        practiceStudent.setClassId(clazz.getId());
//                        practiceStudent.setStudentId(student.getId());
//                        practiceStudent.setStudentName(student.getName());
//
//                        practiceStudents.add(practiceStudent);
//                    }
//                    practiceStudentService.batchInsert(practiceStudents);
//                }
//            }
            //把所有学生设置上classId并放到一起去重在插入
            for (Class clazz : request.getClassStudents()){
                clsIds.add(clazz.getId());
                clsNames.add(clazz.getTitle());
                if (!CollectionUtils.isEmpty(clazz.getStudents())) {
                    for (Student student : clazz.getStudents()) {
                        student.setClassId(clazz.getId());
                        students.add(student);
                    }
                }
            }
            //学生去重
            List<Student> noDupStudents = students.stream().collect(Collectors.collectingAndThen(
                    Collectors.toCollection(
                            () -> new TreeSet<>(Comparator.comparing(Student::getId))),
                    ArrayList::new));
            List<PracticeStudent> practiceStudents = new ArrayList<>();
            for (Student student : noDupStudents){
                PracticeStudent practiceStudent = new PracticeStudent();
                practiceStudent.setPracticeId(practice.getId());
                practiceStudent.setUserId(practice.getUserId());
                practiceStudent.setClassId(student.getClassId());
                practiceStudent.setStudentId(student.getId());
                practiceStudent.setStudentName(student.getName());
                practiceStudents.add(practiceStudent);
            }
            practiceStudentService.batchInsert(practiceStudents);

            if (!CollectionUtils.isEmpty(clsIds)) {
                String clazzIds = clsIds.stream().collect(Collectors.joining(","));
                String clazzNames = clsNames.stream().collect(Collectors.joining(","));
                practice.setClassIds(clazzIds);
                practice.setClassNames(clazzNames);
                this.update(practice);
            }
        }
    }

    public void deleteById(String id) {
        practiceDetailService.deleteByPracticeId(id);
        practiceStudentService.deleteByPracticeId(id);
        practiceStudentResultService.deleteByPracticeId(id);
        this.dao.deleteById(id);
    }

    /**
     * 准备条件
     * @param bean
     * @param qw
     */
    private QueryWrapper prepareParams(PracticeRequest bean, QueryWrapper qw) {
        if(bean.getIds()!=null&&bean.getIds().length>0){
            qw.in("id",bean.getIds());
        }
        if (!StringUtils.isEmpty(bean.getUserId())) {
            qw.eq("user_id", bean.getUserId());
        }
        if (bean.getType() != null) {
            qw.eq("type", bean.getType());
        }
        if (!StringUtils.isEmpty(bean.getPublishMonth())) {
            qw.apply("date_format(publish_time,'%Y-%m') = {0}", bean.getPublishMonth());
        }
        if (!StringUtils.isEmpty(bean.getClassId())) {
            qw.like("class_ids", bean.getClassId());
        }
        if (StringUtils.isNotEmpty(bean.getTitle())){
            qw.like("title",bean.getTitle());
        }
        //发布状态
        if(StringUtils.isNotEmpty(bean.getPublishStatus())){
            String state = bean.getPublishStatus();
            String now =DateUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss");
            switch (state){
                case "1":qw.ge("start_time",now);break;//未发布
                case "2":qw.le("start_time",now);qw.ge("end_time",now);break;//进行中
                case "3":qw.le("end_time",now);break;//已完成
            }
        }
        qw.orderByDesc("publish_time");
        return qw;
    }

    /**
     * 小程序  作业分析
     * @author 赵文博
     * @date 2021/4/22 14:47
     * @param bean
     * @return com.xh.core.bean.XhPage
     **/
    @Override
    public XhPage practiceAnalysis(PracticeRequest bean) {
        XhPage<PracticeDtoVO> xhPage = new XhPage();
        xhPage.setCurrent(bean.getCurrent());
        xhPage.setSize(bean.getSize());
        PracticeDtoVO practiceDtoVO = new PracticeDtoVO();
        bean.setUserId(UserUtils.getCurrentUserId());
        //查询提交率
        List<PracticeDto> practices = this.dao.queryPracticeSubmitRate(xhPage,bean);
        //查询准确率
        double accuracySum = 0.0;//总准确率
        double submitRateSum = 0.0;//总提交率
        double qualifiedSum = 0.0;//总合格率
        Integer submitSum = 0;//总提交数
        if(practices!=null && practices.size() > 0){
            for (PracticeDto practice : practices){
                if(practice.getSubmitRate()==null){
                    practice.setSubmitRate(0.0);
                }
                //查询是否有人作答，没有则不计算
                QueryWrapper<PracticeStudentResult> queryWrapper = new QueryWrapper();
                queryWrapper.eq("practice_id",practice.getId());
                Integer flag = practiceStudentResultService.selectCount(queryWrapper);
                practice.setAccuracy(0.0);
                practice.setQualified(0.0);
                submitSum += practice.getSubmitCount();
                if(flag>0){
                    //正确率
                    double accuracy =  this.dao.queryAccuracy(practice.getId());
                    practice.setAccuracy(accuracy);
                    accuracySum += accuracy;
                    submitRateSum += practice.getSubmitRate();

                    //查询合格率
                    if(practice.getType()!=null){
                        Double qualified = 0.0;
                        if(practice.getType() == 1){
                            //普通作业
//                            qualified = practiceStudentService.queryNormalQualified(practice.getId());
                            qualified = practiceStudentService.queryNormalProficiency(practice.getId());
                            practice.setQualified(qualified);
//                            qualifiedSum += qualified;
                        }else if(practice.getType()==2){
                            //题库作业
                            //获取试卷总分
                            QueryWrapper<Paper> qwPaper = new QueryWrapper<>();
                            qwPaper.eq("id",practice.getPaperId());
                            Paper paper = paperService.selectOne(qwPaper,Paper.class);
                            Integer totalScore = paper.getTotalScore();

                            //获取学生得分
                            if(totalScore>0){
                                Integer qualifiedStudent= 0;//合格学生
                                List<PracticeStudentResult> results = practiceStudentResultService.queryStudentScore(practice.getId());
                                for (PracticeStudentResult result : results){
                                    double temp = result.getScore()/totalScore;
                                    if(temp >= 0.6){
                                        qualifiedStudent++;
                                    }
                                }
                                qualified = ((double)qualifiedStudent/(double)practice.getStudentCount())*100;
                                practice.setQualified(Double.parseDouble(String.format("%.0f", qualified)));
                                qualifiedSum += qualified;
                            }
                        }

                    }
                }
                if(submitSum>0){
                    practiceDtoVO.setAccuracyAvg(Math.ceil(accuracySum / submitSum));//平均正确率
                }
                practiceDtoVO.setSubmitRateAvg(Math.ceil(submitRateSum / practices.size()));//平均提交率
                practiceDtoVO.setQualifiedAvg(Math.ceil(qualifiedSum/practices.size()));//平均合格率
            }

            practiceDtoVO.setPracticeDtoList(practices);
            List<PracticeDtoVO> result = new ArrayList();
            result.add(practiceDtoVO);
            xhPage.setRecords(result);
        }

        return xhPage;
    }

    @Override
    public Boolean deletePracticeById(String id) {
       return this.dao.deletePracticeById(id)>0;
    }

    @Override
    public List queryQuestionByPracticeId(String practiceId, String type) {
        if("2".equals(type)){
            List<QuestionDto> questions = this.dao.queryQuestionByPracticeId(practiceId);
            for (QuestionDto questionDto : questions ){
                if(StringUtils.isNotEmpty(questionDto.getRightAnswerContent())){
                    questionDto.setRightAnswer((JSON) JSON.parse(questionDto.getRightAnswerContent()));
                }
                List<QuestionDto> questionDtoList = questionDto.getChilds();
                for (QuestionDto questionDto1 :questionDtoList){
                    questionDto1.setRightAnswer((JSON) JSON.parse(questionDto1.getRightAnswerContent()));
                }
            }
            return questions;
        }else if("1".equals(type)){
            QueryWrapper<PracticeDetail> qw = new QueryWrapper();
            qw.eq("practice_id",practiceId);
            List practiceDetails = practiceDetailService.selectList(qw,PracticeDetail.class);
            return practiceDetails;
        }
        return null;
    }
}
